package com.umeox.watch.moto.contact.ui;

import static io.agora.rtc.Constants.QUALITY_BAD;
import static io.agora.rtc.Constants.QUALITY_DOWN;
import static io.agora.rtc.Constants.QUALITY_VBAD;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.res.ResourcesCompat;

import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.tencent.mmkv.MMKV;
import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.DeviceManager;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.skin.loader.ResourceManager;
import com.umeox.moto.watch.themes.util.UToast;
import com.umeox.moto.watch.themes.widget.RoundedImageView;
import com.umeox.watch.moto.agora.AgoraService;
import com.umeox.watch.moto.agora.InternalConstants;
import com.umeox.watch.moto.contact.BuildConfig;
import com.umeox.watch.moto.contact.R;
import com.umeox.watch.moto.contact.base.GlideApp;
import com.umeox.watch.moto.contact.model.CallLog;
import com.umeox.watch.moto.contact.model.ContactDetail;
import com.umeox.watch.moto.contact.receiver.PhoneStateReceiver;
import com.umeox.watch.moto.contact.utils.Utils;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.constants.Constants;
import com.umeox.watch.moto.dataservice.proxy.VideocallProxy;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.concurrent.TimeUnit;


public class IncomingCallActivity extends ThemeAppCompatActivity implements View.OnClickListener, PhoneStateReceiver.PhoneStateListener, AgoraService.RemoteVideoStateChangedLister, VolumeSettingDialog.OnVolumeChangeListener {

    //View
    private FrameLayout remoteLayout;
    private ImageView ivAnswer, ivHangup, ivVolume, ivSwitch;

    private RoundedImageView mAvatarIv;
    private TextView mCallingTv, mDurationTv, tvNickname, mMicrophoneIv;

    private VolumeSettingDialog volumeSettingDialog;


    //variable
    private String mChannel; //频道号
    private String friendId; //对方账号
    private boolean videoCall = false, isAnswer = false;

    private Vibrator vibrator;// 振动器
    private MediaPlayer player;
    private ContactDetail contact;

    private AgoraService mAgoraService;
    private AudioManager mAudioManager;
    private PowerManager.WakeLock mWakeLock;
    private boolean mActivelyRefuse;
    private boolean mLifeCycleStart;
    private PowerManager mPowerManager;
    private AlertDialog dialog;

    private VideocallProxy videoCallBinder;
    private boolean peerHangupReceiverIsRegister;
    private View mControlView;
    private int mCurrentVolume;

    private boolean mOriginalRaiseUpOn;
    private boolean mOriginalisOverlayScreenOn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

        PhoneStateReceiver.registerPhoneStateReceiver(this, this);
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if (uri != null) {
            videoCall = InternalConstants.CALL_TYPE_VIDEO.equals(uri.getPath());
            friendId = uri.getQueryParameter(InternalConstants.CALL_QUERY_PARA_FOLLOWER_ID);
            mChannel = uri.getQueryParameter(InternalConstants.CALL_QUERY_PARA_CHANNEL);
        }
        videoCallBinder = (VideocallProxy) VideocallProxy.fetchBinder();
        contact = Utils.getContactByFriendId(friendId);
        if (contact == null) {
            logger("没有找到联系人，退出应用");
            finish();
            return;
        }


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setTurnScreenOn(true);
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

        mAudioManager.requestAudioFocus(null, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);
        mAgoraService = AgoraService.Companion.getInstance(this);

        mAgoraService.setEventHandler(new IncomingEventHandler(this));
        mAgoraService.setRemoteVideoStateChangedListener(this);
        logger("channel=" + mChannel + ", friendId=" + friendId);

        setContentView(R.layout.act_incoming);
        //发送广播通知监听视频来电的应用，目前处于视频来电状态
        sendBroadcast(new Intent(Constants.ACTION_RINGING_VIDEO_CALL));
        registerPeerHangupReceiver();

        initView();
        handleRingingOrVibrate();
        initData();
        remoteLayout.post(() -> {
            if (!mPowerManager.isScreenOn()) {
                mWakeLock = mPowerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "My:Tag");
                mWakeLock.acquire(60 * 1000);
                mWakeLock.setReferenceCounted(false);
            }
        });
        if (TextUtils.equals(mAgoraService.getLastCanceledChannelId(), mChannel)) {
            finish();
        }
        Settings.Global.putInt(getContentResolver(), "isInVideoCall", 1);
        mOriginalRaiseUpOn = DeviceManager.getInstance().isRaiseUpOn();
        mOriginalisOverlayScreenOn = DeviceManager.getInstance().isOverlayScreenOn();
    }

    private void registerPeerHangupReceiver() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_CANCEL_AGORA_CALL);
        registerReceiver(mPeerHangupReceiver, intentFilter);
        peerHangupReceiverIsRegister = true;

    }

    private final BroadcastReceiver mPeerHangupReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            String channel = intent.getStringExtra("channel");
            if (channel.equals(mChannel)) {
                hangup();
            }
        }
    };

    private void initView() {
        remoteLayout = findViewById(R.id.rendererLayout);
        tvNickname = findViewById(R.id.tvNickname);
        mDurationTv = findViewById(R.id.tv_duration);
        mControlView = findViewById(R.id.ll_control);
        mCallingTv = findViewById(R.id.tvDuration);
        ivAnswer = findViewById(R.id.ivAnswer);
        ivHangup = findViewById(R.id.ivHangup);
        ivVolume = findViewById(R.id.ivVolume);
        ivSwitch = findViewById(R.id.camera_switch_iv);
        mMicrophoneIv = findViewById(R.id.iv_microphone);
        mAvatarIv = findViewById(R.id.avatar);
        mCurrentVolume = Utils.getVolume(this);


        if (mCurrentVolume == 0) {
            ivVolume.setImageDrawable(ResourceManager.getInstance().getDrawable(videoCall ? R.drawable.ic_volume_video_mute : R.drawable.ic_volume_mute));
        } else {
            ivVolume.setImageDrawable(ResourceManager.getInstance().getDrawable(videoCall ? R.drawable.ic_volume_video : R.drawable.ic_volume));
        }

        initEvent();
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        remoteLayout.setOnClickListener(this);
        ivHangup.setOnClickListener(this);
        ivAnswer.setOnClickListener(this);
        ivVolume.setOnClickListener(this);
        ivSwitch.setOnClickListener(this);
        mMicrophoneIv.setOnClickListener(this);
        mDurationTv.setVisibility(View.VISIBLE);

    }


    /**
     * 界面控件赋值
     * 接听界面显示用户头像作为背景
     */
    private void initData() {
        Log.d(TAG, "initData: " + videoCall);

        final Drawable callTypeDrawable = ResourcesCompat.getDrawable(getResources(), videoCall ? R.drawable.contact_video : R.drawable.contact_voice, null);
        mCallingTv.setCompoundDrawablesRelativeWithIntrinsicBounds(callTypeDrawable, null, null, null);
        mCallingTv.setText(getResources().getString(R.string.incoming_call));

        tvNickname.setText(contact.getContactName());


        GlideApp.with(this)
                .load(contact.getContactPhotoUrl())
                .placeholder((R.drawable.default_avatar))
                .error(R.drawable.default_avatar)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(mAvatarIv);
    }

    /**
     * sim电话来电或者去掉，需要挂断VoIP电话
     */
    @Override
    public void onCallStateRinging() {
        //logger("通知服务器本方已挂断>>>" + (videoCall ? notifyCancelVideo() : notifyCancelVoip()));
        hangup();
    }

    @Override
    public void onShutdown() {
        //logger("通知服务器本方已挂断>>>" + (videoCall ? notifyCancelVideo() : notifyCancelVoip()));
        hangup();
    }

    @Override
    public void onBackPressed() {
        //logger("通知服务器本方已挂断>>>" + (videoCall ? notifyCancelVideo() : notifyCancelVoip()));
        //hangup();
    }

    /**
     * 根据手表当前设置，决定提醒方式
     */
    private void handleRingingOrVibrate() {
        final int audioTypes = DataProvider.getAudioTypes();
        switch (audioTypes) {
            case 0:
            default:
                startVibrate();
                startRingtone();
                break;
            case 1:
                startVibrate();
                break;
            case 2:
                break;
        }
    }

    /**
     * 接听电话
     * 1.停止响铃和震动
     * 2.隐藏接听按钮
     */
    public void answer() {
        if (!mAgoraService.acceptInvite(mChannel)) {
            logger("正在视频通话中，拒绝邀请");
            mAgoraService.refusedInvite();
            finish();
            return;
        }

        isAnswer = true;
        //停止响铃和震动
        stopRingtone();
        stopVibrate();
        ivAnswer.setVisibility(View.GONE);
        hideControlView();
    }

    private void hideControlView() {
        mDurationTv.setVisibility(View.VISIBLE);
        mControlView.setVisibility(View.VISIBLE);
//        mControlView.removeCallbacks(action);
//        mControlView.postDelayed(action, 5000);

    }


    Runnable action = new Runnable() {
        @Override
        public void run() {
            mControlView.setVisibility(View.GONE);
            mDurationTv.setVisibility(View.GONE);
        }

    };

    /**
     * 挂断或者拒绝接听
     * 如果没有接通，发送拒绝接听事件
     * 释放资源，退出界面
     */
    public void hangup() {
        if (!isAnswer) {
            //没有接通需要发送拒绝接听的事件
            mAgoraService.refusedInvite();
        }
        mActivelyRefuse = true;
        stopRingtone();
        stopVibrate();
        mAgoraService.endCall();
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivAnswer:
                answer();
                break;
            case R.id.ivHangup:
                logger("通知服务器本方已挂断>>>" + (videoCall ? notifyCancelVideo() : notifyCancelVoip()));
                hangup();
                break;
            case R.id.ivVolume:
                if (volumeSettingDialog == null) {
                    volumeSettingDialog = new VolumeSettingDialog(this, isAnswer);
                }
                volumeSettingDialog.setIsAnswer(isAnswer);
                volumeSettingDialog.setOnVolumeChangeListener(IncomingCallActivity.this);
                volumeSettingDialog.show();
                break;
            case R.id.rendererLayout:
                if (!isAnswer) {
                    return;
                }
//                if (mControlView.getVisibility() == View.GONE) hideControlView();

                break;
            case R.id.camera_switch_iv:
                mAgoraService.switchCamera();
                break;
            case R.id.iv_microphone:
                mMicrophoneIv.setSelected(!mMicrophoneIv.isSelected());
                mAgoraService.muteLocalAudioStream(mMicrophoneIv.isSelected());
                break;
            default:
                break;
        }
    }


    /**
     * 开始响铃
     */
    private void startRingtone() {
        try {
            stopRingtone();
            player = new MediaPlayer();
            Uri ringtone = videoCall ? getUriFromDrawableRes(this, R.raw.ringtone_call) : RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            player.setDataSource(this, ringtone);
            player.setAudioStreamType(AudioManager.STREAM_RING);
            player.setLooping(true);
            player.prepare();
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到资源文件中图片的Uri
     *
     * @param context 上下文对象
     * @param id      资源id
     * @return Uri
     */
    public static Uri getUriFromDrawableRes(Context context, int id) {
        Resources resources = context.getResources();
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + resources.getResourcePackageName(id) + "/"
                + resources.getResourceTypeName(id) + "/"
                + resources.getResourceEntryName(id);
        return Uri.parse(path);
    }

    /**
     * 停止响铃
     */
    private void stopRingtone() {
        if (player != null) {
            player.stop();
            player.reset();
            player.release();
            player = null;
        }
    }

    /**
     * 开始震动
     */
    private void startVibrate() {
        long[] pattern = {600, 600, 600, 600};
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(pattern, 0);
    }

    /**
     * 停止震动
     */
    private void stopVibrate() {
        if (vibrator != null) {
            vibrator.cancel();
            vibrator = null;
        }
    }

    /**
     * 通过aidl调用api，上报本次通话时长
     */
    public boolean uploadVideoTime(long startTime, long endTime) {
        VideocallProxy videoCallBinder = (VideocallProxy) VideocallProxy.fetchBinder();
        try {
            return videoCallBinder.uploadVideoTime(friendId, mChannel, startTime, endTime);
        } catch (Exception e) {
            Logger.e("invite join video call failed：" + e);
        }
        return false;
    }


    @Override
    protected void onStop() {
        super.onStop();
        mLifeCycleStart = mPowerManager.isScreenOn();
        logger("onStop:" + this);

        if (mLifeCycleStart) {
            mAgoraService.stopPreview();
            stopRingtone();
            stopVibrate();
        }
    }

    private static final String TAG = "IncomingCallActivity";

    @Override
    protected void onDestroy() {
        super.onDestroy();
        logger("onDestroy");
        Settings.Global.putInt(getContentResolver(), "isInVideoCall", 0);
        if (mOriginalRaiseUpOn) {
            DeviceManager.getInstance().setRaiseUpValue(true);
        }
        if(mOriginalisOverlayScreenOn){
            DeviceManager.getInstance().setOverlayScreenValue(true);
        }
        stopRingtone();
        stopVibrate();

        mActivelyRefuse = false;
        if (mAgoraService == null) {
            AgoraService.Companion.getInstance(this).resetCallState();
        } else {
            mAgoraService.resetCallState();
            mAgoraService.setEventHandler(null);
            mAgoraService.stopPreview();
        }


        if (mAudioManager != null) {
            mAudioManager.abandonAudioFocus(null);
        }
        if (mWakeLock != null) {
            mWakeLock.release();
        }
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        PhoneStateReceiver.unRegisterPhoneStateReceiver(this);
        if (peerHangupReceiverIsRegister && mPeerHangupReceiver != null) {
            unregisterReceiver(mPeerHangupReceiver);
            peerHangupReceiverIsRegister = false;
        }

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

    }

    private void logger(String text) {
        Logger.w(text);
    }

    @Override
    public void remoteVideoMuted() {
        //对方已停止推送视频流
        Logger.e(TAG, "对方已停止推送视频流");

        runOnUiThread(() -> {
            if (remoteLayout.getChildCount() > 0) {
                remoteLayout.removeAllViews();
                mAgoraService.disableVideo();

                videoCall = false;
                mAgoraService.setCallType(AgoraService.CALL_TYPE_VOICE);
                mAgoraService.sendSwitchMsg2Peer();
            }

            ivSwitch.setVisibility(View.GONE);
            mMicrophoneIv.setVisibility(View.VISIBLE);
            ivVolume.setImageDrawable(mCurrentVolume == 0 ? ResourceManager.getInstance().getDrawable(R.drawable.ic_volume_mute) : ResourceManager.getInstance().getDrawable(R.drawable.ic_volume));
            mAvatarIv.setVisibility(TextView.VISIBLE);
//            final Drawable callTypeDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.contact_voice, null);
//            mCallingTv.setCompoundDrawablesRelativeWithIntrinsicBounds(callTypeDrawable, null, null, null);
//            mCallingTv.setVisibility(View.VISIBLE);

//            remoteLayout.setBackground(ResourceManager.getInstance().getDrawable(R.drawable.voip_call_main_bg));
        });

    }

    @Override
    public void onVolumeChanged(int volumeValue) {
        mCurrentVolume = volumeValue;
        if (volumeValue == 0) {
            ivVolume.setImageDrawable(videoCall ? ResourceManager.getInstance().getDrawable(R.drawable.ic_volume_video_mute) : ResourceManager.getInstance().getDrawable(R.drawable.ic_volume_mute));
        } else {
            ivVolume.setImageDrawable(videoCall ? ResourceManager.getInstance().getDrawable(R.drawable.ic_volume_video) : ResourceManager.getInstance().getDrawable(R.drawable.ic_volume));
        }
    }


    private class IncomingEventHandler extends AgoraService.IncomingCallEventHandler {
        private final WeakReference<IncomingCallActivity> reference;
        private int mUid;

        private IncomingEventHandler(IncomingCallActivity activity) {
            reference = new WeakReference<>(activity);

        }

        @Override
        public void onUserJoined(int uid) {
            mUid = uid;
            isAnswer = true;
            try {
                runOnUiThread(() -> {
                    if (!videoCall) {
                        showCallDuration();
                    }

                });
            } catch (Exception e) {
                Log.e(TAG, "onUserJoined: ", e);
            }
        }

        @Override
        public void onFirstRemoteFrame(int uid) {
            try {
                runOnUiThread(() -> {
                    showCallDuration();
                    remoteLayout.setForeground(null);
                    logger("绑定远端图像>>>" + mAgoraService.setupRemoteVideo(remoteLayout, uid));
                    mAgoraService.startPreview();
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onTiming(final int aLong) {
            try {
                runOnUiThread(() -> {
                    long hour = TimeUnit.SECONDS.toHours(aLong);
                    long minute = TimeUnit.SECONDS.toMinutes(aLong);
                    mDurationTv.setText(String.format(Locale.getDefault(), "%1$02d:%2$02d:%3$02d", hour,minute, aLong % TimeUnit.MINUTES.toSeconds(1)));
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @NotNull
        private String getFormat(long aLong) {
            return String.format(Locale.US, "%02d", aLong);
        }

        @Override
        public void onInviteEnd() {
            try {
                logger("对方已结束呼叫，退出应用");
                mAgoraService.endCall();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                finish();
            }
        }

        @Override
        public void onCallEnd(int totalDuration) {
            try {
                if (!isFinishing()) {
                    finish();
                }
                logger("视频通话结束>>>" + totalDuration);
                final long endTime = System.currentTimeMillis();
                long startTime = endTime - TimeUnit.SECONDS.toMillis(totalDuration);
                if (totalDuration > 0) {
                    CallLog.insert(friendId,
                            startTime, endTime,
                            videoCall ? InternalConstants.CallType.INCOMING_VIDEO_CALL : InternalConstants.CallType.INCOMING_VOIP_CALL);
                    if (totalDuration >= 30) {
                        MMKV.defaultMMKV().putLong(friendId, SystemClock.elapsedRealtime());
                    }
                    //logger("上传视频通话时间>>>" + uploadVideoTime(startTime, endTime));
                    return;
                }

                if (mActivelyRefuse) {
                    return;
                }
                CallLog.insert(friendId,
                        System.currentTimeMillis(),
                        System.currentTimeMillis(),
                        videoCall ? InternalConstants.CallType.VIDEO_MISSED_TYPE : InternalConstants.CallType.VOIP_MISSED_TYPE);


            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onWarning(int warn) {
            Log.w(TAG, "Contact RTC onWarning: " + warn);
        }

        @Override
        public void switch2VideoMode(int mode) {
            Log.e(TAG, "对方邀请切换为视频模式:" + mode);
            if (mode == 0) {
                runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(IncomingCallActivity.this)
                            .setIcon(R.drawable.contact_video)
                            .setTitle("Tips")
                            .setMessage("对方邀请切换为视频模式")
                            .setPositiveButton("OK", (dialog, which) -> {
                                mAgoraService.acceptSwitch2Video();
                                remoteLayout.setForeground(null);
                                mAgoraService.setupRemoteVideo(remoteLayout, mUid);
                                dialog.dismiss();
                            })
                            .setNegativeButton("Refuse", (dialog, which) -> {
                                mAgoraService.refuseSwitch2Video();
                                dialog.dismiss();
                            });
                    dialog = builder.create();
                    dialog.show();
                });
            }
        }

        @Override
        public void onNetworkQuality(int uid, int txQuality, int rxQuality) {
            if (txQuality == QUALITY_BAD || txQuality == QUALITY_VBAD || txQuality == QUALITY_DOWN
                    || rxQuality == QUALITY_BAD || rxQuality == QUALITY_VBAD || rxQuality == QUALITY_DOWN) {
               if(BuildConfig.DEBUG){
                   try {
                       runOnUiThread(() -> UToast.show(getString(R.string.str_poor_connection), Toast.LENGTH_SHORT));
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
            }
        }

        @Override
        public void onPeerNoResponse() {

        }

        @Override
        public void onInviteTimeout() {

        }
    }

    private void showCallDuration() {
        mDurationTv.setVisibility(View.VISIBLE);
        mCallingTv.setVisibility(View.GONE);
        ivVolume.setVisibility(View.VISIBLE);
        if (videoCall) {
//            ivSwitch.setVisibility(View.VISIBLE);
            mMicrophoneIv.setVisibility(View.GONE);
            mAvatarIv.setVisibility(TextView.INVISIBLE);
        } else {
            ivSwitch.setVisibility(View.GONE);
            mMicrophoneIv.setVisibility(View.VISIBLE);
        }

        if (mOriginalRaiseUpOn) {  //翻腕功能本身是开启的
            DeviceManager.getInstance().setRaiseUpValue(false);
        }
        if(mOriginalisOverlayScreenOn){
            DeviceManager.getInstance().setOverlayScreenValue(false);
        }
    }


    /**
     * 通过aidl调用api通知app取消当前通话
     */
    public boolean notifyCancelVideo() {
        if (videoCallBinder != null) {
            try {
                return videoCallBinder.notifyCancelVideo(friendId, mChannel);
            } catch (Exception e) {
                e.printStackTrace();
                Logger.e("notify cancel video call failed：" + e);
            }
        }
        return false;
    }

    /**
     * 通过aidl调用api通知app取消当前通话
     */
    public boolean notifyCancelVoip() {
        if (videoCallBinder != null) {
            try {
                return videoCallBinder.notifyCancelVoip(friendId, mChannel);
            } catch (Exception e) {
                e.printStackTrace();
                Logger.e("notify cancel voice call failed：" + e);
            }
        }
        return false;
    }

    @Override
    protected void registerUnbindAndDisableReceiver(boolean register) {

    }
}